package com.bosicloud.cmb.ibp.edge.config;

import com.alibaba.fastjson.JSON;
import com.bosicloud.cmb.ibp.commom.dto.UnionResult;
import com.bosicloud.cmb.ibp.edge.constant.SessionKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Slf4j
public class AuthIntercept implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
                             Object obj) throws Exception {

        HttpSession session = req.getSession(false);

        if(null == session) {
            response(resp, "未找到会话信息.");
            return false;
        }

        if (session.getAttribute(SessionKeys.ACCOUNT) != null) {
            return true;
        } else {
            response(resp, "未登录或登录超时.");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private void response(HttpServletResponse resp, String content) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new UnionResult(UnionResult.StatusEnum.FailToken, content)));
    }

    private String getBasepath(HttpServletRequest req) {

        return req.getScheme() + "://"
                + req.getServerName() + ":"
                + req.getServerPort() + req.getContextPath();
    }

}
